<template>
  <div class="chart" style="height: 350px; width: 100%" />
</template>

<script>
import echarts from "echarts";
import { urlObj } from "@/api/login";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    chartData: {
      type: Object,
      default: {},
    },
    dataInput: {
      type: Number | String,
      default: 2,
    },
    databutton: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      chart: null,
      newminute: "", //当前时间
      newminute2: "", //2小时前
      socObj: [], //soc数据
      ahObj: [], //容量数据
      temObj: [], //温度数据
      // dataInput: 24, //获取多少个小时的数据  默认2小时
      newData: {
        xAxis: [],
        yAxis: [
          {
            name: "SOC",
            value: [],
          },
          {
            name: "容量",
            value: [],
          },
          {
            name: "pcd温度",
            value: [],
          },
          {
            name: "外壳温度",
            value: [],
          },
          {
            name: "电芯温度",
            value: [],
          },
        ],
        yAxisName: "SOC(%)/AH/℃",
      },
      legendData: [],
      seriesData: [],
      colorArr: [
        "#8E35FF",
        "#FFB933",
        "#44C558",
        "#2F8FFF",
        "#435325",
        "#987678",
      ],
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
    databutton: {
      deep: true,
      handler(val) {
        if (val) {
          //搜索
          this.init();
          setTimeout(() => {
            this.databutton = false;
          }, 2000);
        }
      },
    },
  },
  created() {
    this.init(); //请求合集
  },
  mounted() {
    // console.log(1111, this.dataInput);
    setTimeout(() => {
      this.$nextTick(() => {
        this.initChart();
      });
    }, 800);
    this.legendData = this.newData.yAxis.map((item) => item.name);
    this.seriesData = this.newData.yAxis.map((item1, index1) => {
      return {
        name: item1.name,
        type: "line",
        symbol: "circle",
        symbolSize: 6,
        itemStyle: {
          color: this.colorArr[index1],
        },
        lineStyle: {
          width: 4,
        },
        data: item1.value, // 折线图的数据
      };
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    // 请求合集
    init() {
      this.getCurrentTime(0); //获取当前时间
      this.getCurrentTime(this.dataInput); //获取多少个小时的数据
      // 获取soc、容量、温度数据:图表数据类型  POS：位置  SOC：电量 AH:容量  TEM：温度
      this.listData("SOC", this.dataInput);
      this.listData("AH", this.dataInput);
      this.listData("TEM", this.dataInput);
      setTimeout(() => {
        this.$nextTick(() => {
          this.initChart();
        });
      }, 1000);
      setTimeout(() => {
        this.$nextTick(() => {
          this.initChart();
        });
      }, 2000);
    },

    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions({ expectedData, actualData } = {}) {
      this.chart.setOption({
        backgroundColor: "#fff",
        grid: {
          containLabel: true,
          bottom: "1%",
          top: "15%",
          left: "1%",
          right: "1%",
        },
        dataZoom: [
          {
            // 这是一个放大缩小的控制区域
            type: "inside", // 表示这是 slider 类型
            filterMode: "filter",
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          top: "1%",
          right: "1%",
          data: this.legendData,
          itemGap: 10,
          textStyle: {
            fontSize: 11,
            color: "#888",
          },
        },
        xAxis: {
          triggerEvent: true,
          data: this.newData.xAxis || [],
          axisLabel: {
            showMaxLabel: true,
            showMinLabel: true,

            interval: this.xAxisFn(),
            show: true,
            fontSize: 11,
            rotate: 30,
            color: "#888",
          },
          axisLine: {
            show: false,
            lineStyle: {
              show: false,
              color: "#F3F3F3",
              width: 2,
            },
          },

          axisTick: {
            show: false,
          },
        },
        yAxis: [
          {
            name: this.newData.yAxisName,
            type: "value",
            nameTextStyle: {
              color: "#888",
              fontSize: 11,
              padding: [0, 0, 0, 20],
            },
            splitNumber: 6,
            axisLabel: {
              show: true,
              fontSize: 11,
              color: "#888",
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: "#aaa",
                type: "dotted",
              },
            },
          },
        ],
        series: this.seriesData,
      });
    },
    // 获取x轴的显示长度
    xAxisFn() {
      let a = this.newData.xAxis.length || 0; //拿x轴数组的长度
      let a1 = a - 1;
      if (a <= 12) {
        return 0;
      } else {
        //x轴数组的长度最多显示12个，当大于12小于等于24，为隔1个显示1个；当大于24小于等于36，为隔2个显示1个，以此类推...
        let n = Math.floor(a / 12); //拿x轴数组的长度与12的倍数
        let m = a % 12; //拿x轴数组的长度与12的余数
        // console.log("x轴的长度，12的倍数与余数", a, n, m, this.newData.xAxis);
        if (m !== 0 && m < 12) {
          return n;
        } else {
          return n - 1;
        }
      }
    },

    // 获取soc、容量、温度数据
    listData(type, num) {
      // num = 4 为 48条  最多48条
      // let a = 0;
      // if (num > 4) {
      //   let n = Math.floor(num / 4);
      //   let m = num % 4;
      //   if (m !== 0 && m < 4) {
      //     a = n;
      //   } else {
      //     a = n - 1;
      //   }
      // }

      let prarms = {
        func: "getChart",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          chart_type: type || "", //图表数据类型  POS：位置  SOC：电量 AH:容量  TEM：温度
          s_time: this.newminute2 || "", //开始时间
          e_time: this.newminute || "", //结止时间
          battery_id: this.chartData.id || "", //电池编号
          density: 0, //数据间隔 0：5分 1：10分 以此类推},    num <= 4 ? 0 : a
        },
      };
      urlObj(prarms).then((res) => {
        let obj = res.result || [];
        // this.getTimesArray(this.dataInput); // 获取x轴间隔
        this.newData.xAxis = [];
        if (obj.length !== 0) {
          obj.forEach((item) => {
            let a = item.update_time.split(" ")[1].split(":")[0];
            let b = item.update_time.split(" ")[1].split(":")[1];
            this.newData.xAxis.push(a + ":" + b);
          });
        }

        if (type == "SOC") {
          this.socObj = obj;
          if (this.socObj.length !== 0) {
            this.socObj.forEach((item) => {
              this.newData.yAxis[0].value.push(item.soc);
            });
          }
        }
        if (type == "AH") {
          this.ahObj = obj;
          if (this.ahObj.length !== 0) {
            this.ahObj.forEach((item) => {
              let ah = item.ah / 100;
              this.newData.yAxis[1].value.push(ah);
            });
          }
        }
        if (type == "TEM") {
          this.temObj = obj;
          if (this.temObj.length !== 0) {
            this.temObj.forEach((item) => {
              let pcb_t = item.pcb_t;
              let shell_t = item.shell_t;
              let cell_t = item.cell_t;
              this.newData.yAxis[2].value.push(pcb_t);
              this.newData.yAxis[3].value.push(shell_t);
              this.newData.yAxis[4].value.push(cell_t);
            });
          }
        }
      });
    },

    // 获取年月日时分秒
    getCurrentTime(val) {
      let date = new Date(new Date().getTime() - val * 60 * 60 * 1000);
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
      let minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
      let second = date.getSeconds(); // 秒
      second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
      let da =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        ":" +
        minute +
        ":" +
        second;
      if (val !== 0) {
        this.newminute2 = da;
      } else {
        this.newminute = da;
      }
    },
    // 获取x轴间隔
    getTimesArray(val) {
      this.newData.xAxis = [];
      const now = new Date().getTime(); //当前时间戳
      const twoHoursAgo = now - val * 60 * 60 * 1000; // 当前时间减去多少个小时前的时间戳
      const cha = now - twoHoursAgo; //时间戳差
      const jiange = 5 * 60 * 1000; //间隔多少（秒或者分钟） 5分钟
      const xunhuai = Math.floor(cha / jiange); //循坏多少次
      for (let i = 0; i < xunhuai + 1; i++) {
        let dat = this.getCurrentTime1(twoHoursAgo + i * jiange);
        this.newData.xAxis.push(dat);
      }
    },
    // 转化时间戳
    getCurrentTime1(val) {
      let date = new Date(val);
      let hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
      let minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
      let da = hour + ":" + minute;
      return da;
    },
  },
};
</script>
